package com.itheima.wisdomnext.service.ImpI; // 需要注意类路径大小写

import com.itheima.wisdomnext.entity.Follow;
import com.itheima.wisdomnext.entity.Result.enumcalss.ErrorCode;
import com.itheima.wisdomnext.mapper.FollowMapper;
import com.itheima.wisdomnext.service.FollowService;
import com.itheima.wisdomnext.util.FollowS_Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FollowServiceImpl implements FollowService {

    @Autowired
    private FollowMapper followMapper;

    @Override
    public List<Follow> getAllFollowers(Integer userId) {
        return followMapper.getAllFollowers(userId);  // 更正方法名称
    }

    @Override
    public List<Follow> getAllFollowed(Integer userId) {
        // 获取所有关注了当前用户的用户列表
        List<Follow> followedUsers = followMapper.getAllFollowed(userId);

        if (followedUsers == null || followedUsers.isEmpty()) {
            FollowS_Util.isTrue(true, ErrorCode.FAILED, "获取所有关注了当前用户的用户列表失败");
        }

        // 遍历所有被关注的人，检查是否也关注了当前用户
        for (Follow followedUser : followedUsers) {
            Integer followedUserId = followedUser.getFollowerId(); // 关注当前用户的人 ID

            // 查询该被关注的用户是否关注当前用户
            Integer isFollowing = followMapper.countFollowersByFollowerId(userId, followedUserId);

            // 设置 isFollowing，如果关注数大于等于 1，则为 true，否则不设置（默认 false）
            followedUser.setIsFollowing(isFollowing != null && isFollowing >= 1);
        }
        return followedUsers;
    }

    @Override
    public void followUser(Integer followerId, Integer followedId) {
        // 首先检查用户是否已经关注了该用户
        Follow existingFollow = followMapper.findByFollowerIdAndFollowedId(followerId, followedId);
        if (existingFollow != null) {
            FollowS_Util.isTrue(true,ErrorCode.FAILED,"用户已关注了该用户");
        }

        // 创建关注记录
        Follow follow = new Follow();
        follow.setFollowerId(followerId);
        follow.setFollowedId(followedId);
        followMapper.followUser(follow);
    }

    @Override
    public void unfollowUser(Integer followerId, Integer followedId) {
        Follow follow = followMapper.findByFollowerIdAndFollowedId(followerId, followedId);
        if (follow == null) FollowS_Util.isTrue(true,ErrorCode.FAILED,"没有找到关注记录");
        followMapper.unfollowUser(followerId, followedId);
    }

    // 检查用户是否关注该帖子的作者
    public boolean isUserFollowing(int userId, int authorId) {
        return followMapper.isUserFollowing(userId, authorId) > 0;
    }
}
